package cn.j0n4than.accountingtool.controller.api.user;

import cn.j0n4than.accountingtool.config.ResponseConfig;
import cn.j0n4than.accountingtool.entity.Spending;
import cn.j0n4than.accountingtool.pojo.request.UserSpendingAddRequest;
import cn.j0n4than.accountingtool.utils.Response;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;

/**
 * 用户消费控制器
 *
 * @author jonathan
 */
@Slf4j
@RestController
@RequestMapping("/api/user/spending")
public class UserSpendingController extends UserBaseController {

    /**
     * 获取消费的分页列表
     *
     * @param spending 搜索条件
     * @param page     页码
     * @param size     页数据
     * @return Response
     */
    @PostMapping("/getList/{page}/{size}")
    public Response getList(@RequestBody Spending spending, @PathVariable Integer page, @PathVariable Integer size) {
        Response response = Response.success();
        //覆盖用户传进来的userId参数，要不然用户想查谁就查谁
        spending.userId = this.getCurrentUser().id;
        Page<Spending> spendingPage = this.spendingService.getPageWithType(spending, page, size);
        return response.setResult("spendingList", spendingPage);
    }

    /**
     * 添加支出
     *
     * @return Response
     */
    @PostMapping("/add")
    public Response add(
            @Validated @RequestBody UserSpendingAddRequest userSpendingAddRequest,
            BindingResult bindingResult
    ) {
        Response response = Response.response();
        checkValidate(response, bindingResult);
        if (response.getStatus() == ResponseConfig.ERROR) {
            return response;
        }

        //判断金额是否小于等于0
        if (userSpendingAddRequest.amount.compareTo(new BigDecimal(0)) < 1) {
            return response.setStatus(ResponseConfig.ERROR).setMessage("金额不正确");
        }

        Spending spending = new Spending();
        spending.userId = getCurrentUser().id;
        spending.amount = userSpendingAddRequest.amount;
        spending.typeId = userSpendingAddRequest.typeId;
        spending.note = userSpendingAddRequest.note;

        if (this.spendingService.insert(spending) > 0) {
            response.setStatus(ResponseConfig.SUCCESS).setMessage("添加支出成功");
        } else {
            response.setStatus(ResponseConfig.ERROR).setMessage("未知错误");
        }
        return response;
    }
}
